#compdef epro ego

# vim: set et sw=2 sts=2 ts=2 ft=zsh :
# ZSH completion for ego(8)

local portdir=$(python -c 'import portage;print(portage.settings["PORTDIR"])')
local profile_dir="funtoo/1.0/linux-gnu"

_ego-modulelist() {
  local -a modules

  modules=( 'profile' 'sync' 'query' 'info' 'help' )

  _values 'Modules' $modules && ret=0
}

_epro-actionlist() {
  local -a actions

  actions=( 'show' 'show-json' 'get' 'list' 'flavor' 'mix-ins' 'subarch' 'arch' )

  [[ $curcontext == ":complete:ego-profile:" ]] && actions=( 'info' 'help' $actions )

  _values 'Actions' $actions && ret=0
}

_epro-profile-choices() {
  local -a profiles

  profiles=( 'flavor' 'mix-ins' 'subarch' 'arch' )

  _values 'Profiles' $profiles && ret=0
}

_epro-fetch-choices() {
  local profile=$1
  local -a choices

  choices=("$portdir"/profiles/$profile_dir/$profile/*(/N:t))

  _values "Choices" $choices && ret=0
}

_epro-mixins-choices() {
  local -a mixins
  local -a choices

  choices=()
  mixins=("$portdir"/profiles/$profile_dir/mix-ins/*(/N:t))
  for choice in $mixins; do
    choices=(+$choice -$choice $choices)
  done

  _values "Choices" $choices && ret=0
}

_epro-subarch-choices() {
  _epro-fetch-choices arch/$(epro get arch)/subarch
}

_ego-profile() {
  local curcontext="$curcontext" ret=1

  if ((CURRENT == 2)); then
    _epro-actionlist
  elif ((CURRENT == 3)); then
    if [[ $words[2] == (list|get) ]]; then
      _epro-profile-choices
    elif [[ $words[2] == mix-ins ]]; then
      _epro-mixins-choices
    elif [[ $words[2] == subarch ]]; then
      _epro-subarch-choices
    elif [[ $words[2] == (flavor|arch) ]]; then
      _epro-fetch-choices $words[2]
    fi
  elif ((CURRENT > 3)); then
    if [[ $words[2] == list ]]; then
      _epro-profile-choices
    fi
  fi
}

_equery-actionlist() {
  local -a actions

  actions=( 'versions' 'origin' 'bugs' )

  _values 'Actions' $actions && ret=0
}

_ego-query() {
  local curcontext="$curcontext" ret=1
  if ((CURRENT == 2)); then
    _equery-actionlist
  fi
}

_ego() {
  local curcontext="$curcontext" ret=1

  if ((CURRENT == 2)); then
    _ego-modulelist
  else
    shift words
    (( CURRENT -- ))
    curcontext="${curcontext%:*:*}:ego-$words[1]:"
    _call_function ret _ego-$words[1]
  fi
}

compdef _ego-profile epro
compdef _ego ego
